<template>
  <ele-modal
    form
    :width="600"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <ele-page>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="付款凭证" prop="images">
          <image-upload :limit="10" v-model="form.images" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="save">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </ele-page>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { returnMoney } from '@/api/company';
  import { EleMessage } from 'ele-admin-plus/es';
  import ImageUpload from '@/components/ImageUpload/index.vue';

  import { useFormData } from '@/utils/use-form-data';

  const emit = defineEmits(['done', 'update:modelValue']);
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    type: String
  });

  const title = ref('');

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields] = useFormData({
    ids: 0,
    images: '', // 付款凭证
    amount: 0
  });

  const rules = reactive({
    images: [
      {
        required: true,
        message: '请上传凭证',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 提交 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      var requestData = Object.assign({}, form);
      returnMoney(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          console.log(e);
        });
    });
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          form.id = props.data.id;
          form.plate_number = props.data.plate_number;
          form.amount = props.data.amount;
          form.images = '';
        }
        title.value = props.data.plate_number + '多收返还';
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
        console.log('关闭');
      }
    }
  );
</script>
